<template>
	<view class="content">
		<view class="main">

			<view style="font-weight: bold;color: orangered;">注意：图片识别不能保证准确性，请认真核对识别后的数据与销售单是否一致！</view>
			<view class="menu_name">
				上传销售单
				<view style="font-size: 24rpx;color: #aaa;margin: 0 0 0 6rpx;">点击图片查看大图</view>
			</view>
			<view class="item_sel_img">
				<view v-if="img_url" class="sel_img_div">
					<image class="sel_img" :src="img_url" @click="onPreviewImg(0)"></image>
					<view style="display: none;" class="sel_img_del" @click="onDelImg(0)">删除</view>
				</view>
			</view>
			<button class="btn_sel_media" @click="onSelImg">选择照片</button>

			<!-- 收货人部分 -->
			<view class="item_div">

				<view class="item_sub_div">
					<view class="item_sub_txt">客户姓名</view>
					<input class="et_sub_txt" placeholder="请输入客户姓名(名称)" maxlength="99" @input="onInputReceiverName" :value="info.receiver_name" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">收货电话</view>
					<input class="et_sub_txt" placeholder="请输入收货人电话" type="digit" maxlength="16" @input="onInputReceiverMobile" :value="info.receiver_mobile" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">收货地址</view>
				</view>

				<view class="item_sub_div">
					<view class="item_sub_txt" style="display: none;">详细地址</view>
					<textarea class="et_sub_txt" style="width: 100%;;" placeholder="请输入收货地址" @input="onInputReceiverAddress" :value="info.receiver_address" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">货物名称</view>
					<input class="et_sub_txt" placeholder="请输入货物名称" maxlength="666" @input="onInputGoodsName" :value="info.goods_name" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">总件数</view>
					<input class="et_sub_txt" placeholder="请输入总件数" type="digit" maxlength="666" @input="onInputNum" :value="info.num" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">总重量(kg)</view>
					<input class="et_sub_txt" placeholder="请输入总重量" type="digit" maxlength="16" @input="onInputWeight" :value="info.weight" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

				<view class="item_sub_div">
					<view class="item_sub_txt">总体积(m³)</view>
					<input class="et_sub_txt" placeholder="请输入总体积" type="digit" maxlength="16" @input="onInputVolume" :value="info.volume" />
				</view>

				<view style="width: 100%;height: 1rpx;background: #ededed;margin: 0rpx 0 0 0;"></view>

			</view>

			<view class="btn_ok" @click="onOK">确定</view>
			<view class="btn_ok" style="display: none;margin: 24rpx 0 0 0;" @click="onOK2">DeepSeek对话</view>

			<!-- <view>{{message}}</view> -->
			<rich-text style="margin: 24rpx" :nodes="message"></rich-text>

		</view>

	</view>
</template>

<script>
	import { getUInfo, isEmpty } from '@/util/util.js'
	import { chooseAndUploadImg, chooseAndUploadVideo } from '@/util/uni_util.js'
	const CryptoJS = require('@/util/ext/crypto-js.min.js')
	export default {
		data() {
			return {
				order_sn: '', // 运单号
				query_num: '', // 查货单号
				detail: {}, // 运单详情
				img_url: '', // 选择的照片

				// 开单信息
				info: {
					receiver_name: '',
					receiver_mobile: '',
					receiver_address: '',
					goods_name: '火腿肠',
					num: '',
					weight: '',
					volume: 1,
				},

				message: '', // deepseek生成的内容
			}
		},

		mounted() {},

		onLoad(opts) {
			// 扫码
			uni.$on('onGetQrCode', (data) => {
				let { qr_code, od_num, startCity, toCity, goods } = JSON.parse(data.qr_code_data)
				this.order_sn = od_num
				this.query_num = qr_code
				this.detail = { startCity, toCity, goods }
				console.log('this.detail  = ', this.detail);
			})
		},

		onUnload() {
			uni.$off('onGetQrCode', () => {})
		},

		methods: {

			// 输入货物名称
			onInputGoodsName(e) {
				this.info.goods_name = e.detail.value
			},
			// 输入件数
			onInputNum(e) {
				this.info.num = e.detail.value
			},
			// 输入体积
			onInputVolume(e) {
				this.info.volume = e.detail.value
			},
			// 输入重量
			onInputWeight(e) {
				this.info.weight = e.detail.value
			},
			// 输入收货人地址
			onInputReceiverAddress(e) {
				this.info.receiver_address = e.detail.value
			},
			// 监听:收货电话
			onInputReceiverMobile(e) {
				this.info.receiver_mobile = e.detail.value
			},
			// 监听:收货客户名称
			onInputReceiverName(e) {
				this.info.receiver_name = e.detail.value
			},
			// 监听:输入单号
			onInputOrder(e) {
				this.order_sn = e.detail.value
				if (!this.order_sn) {
					this.detail = {}
				}
			},
			// 查询运单
			onQueryWb() {
				uni.navigateTo({ url: '/pages/sys/scan_qrcode?type=2' })
			},
			// 选择上传照片
			async onSelImg() {
				let res = await chooseAndUploadImg()
				// console.log('上传结果 = ', res);
				this.img_url = res
				// this.fetchPicWord()
				// this.dsAnalyze()
				this.arkAnalyze()
			},
			// 预览照片
			onPreviewImg(current) {
				uni.previewImage({
					current,
					urls: [this.img_url],
					success: (res) => {},
					fail: (res) => {
						uni.showToast({ icon: 'none', title: '查看图片失败' })
					}
				})
			},
			// 删除照片
			onDelImg(index) {
				let that = this
				uni.showModal({
					title: '提示',
					content: '是否删除该照片？',
					success: (res) => {
						if (res.confirm) {
							that.img_url = ''
						}
					},
				})
			},

			// 提交上报
			onOK() {
				if (!this.order_sn) {
					uni.showToast({ icon: 'none', title: '请输入运单号' })
					return
				}
				if (!this.img_url) {
					uni.showToast({ icon: 'none', title: '请上传照片' })
					return
				}
				uni.showModal({
					title: '提示',
					content: '确认提交以上信息？',
					success: (res) => {
						res.confirm && this.postData()
					}
				})
			},

			onOK2() {
				this.dsChatCompletions()
				// this.arkAnalyze()
			},

			// 接口:火山引擎(豆包AI)
			async arkAnalyze() {
				let that = this
				uni.showLoading({ title: '识别中..', mask: true, })
				let user_token = getUInfo().token

				let image_url = this.img_url
				let text = '分析图片中的客户名称、客户地址、客户电话、总件数、总重量，以json格式输出，键名分别为name，address，phone，num，weight'

				let response = await that.$arkAnalyze2({ image_url, text })
				if (response.code == 1) {
					let res = JSON.parse(response.data)
					if (res && res.choices && res.choices.length > 0 && res.choices[0].message && res.choices[0].message.content) {
						let contentObj = null
						try {
							contentObj = JSON.parse(res.choices[0].message.content)
						} catch (e) {}
						if (contentObj) {
							that.info.receiver_name = contentObj.name
							that.info.receiver_mobile = contentObj.phone
							that.info.receiver_address = contentObj.address
							that.info.num = contentObj.num
							that.info.weight = contentObj.weight
							uni.showToast({ title: '图片识别成功', icon: 'none', duration: 3000 })
						}
					}
				} else {
					// uni.showToast({ title: '图片识别失败', icon: 'none' })
					uni.showModal({
						title: '提示',
						content: `图片识别失败！请检查图片是否清晰，或联系技术人员。错误信息：${response.msg}`,
						showCancel: false,
						success: (res) => {}
					})
				}
			},

			// 检索打印数据:收货电话,地址,重量,体积
			analysisPrintData(print_data) {
				let that = this
				print_data.map((item, index) => {
					if (item.result.includes('电话') && !item.result.includes('司机电话')) {
						console.log('电话.item = ', item);
						let phone = item.result
						phone = phone.replace('电话', '')
						phone = phone.replace(':', '')
						phone = phone.replace('：', '')
						that.info.receiver_mobile = phone
					}
					if (item.result.includes('地址')) {
						console.log('地址.item = ', item);
						let address = item.result
						address = address.replace('地址', '')
						address = address.replace(':', '')
						address = address.replace('：', '')
						that.info.receiver_address = address
					}
					if (item.result.includes('合计')) {
						console.log('合计.item = ', item);
						try {
							this.info.num = print_data[index + 1].result
						} catch (error) {}
						try {
							this.info.weight = print_data[index + 2].result
						} catch (error) {}
					}
				})
			},

			// 检索表格数据:收货电话,地址,重量,体积
			analysisTableData(table_data) {
				let that = this
				table_data.map((item, index) => {
					// console.log('解析表格数据 = ', item);
					if (item.lines && item.lines.length > 0) {
						// 解析地址
						if (item.lines[0].text.includes('合计')) {
							console.log('合计.item = ', item);
							let address = item.lines[0].text
							address = address.replace('地址', '')
							address = address.replace(':', '')
							address = address.replace('：', '')
							that.info.receiver_address = address
						}
					}
				})
			},

			// 接口:AI图片识别
			async dsAnalyze() {
				let that = this
				uni.showLoading({ title: '识别中..', mask: true, })
				let user_token = getUInfo().token

				let image_url = this.img_url

				let res = await that.$dsAnalyze({ image_url })
				if (res.result == 1) {

				} else {
					uni.showToast({ title: 'DS识别失败', icon: 'none' })
				}
			},

			// 接口:deepseek对话
			async dsChatCompletions() {
				let that = this
				uni.showLoading({ title: '生成中..', mask: true, })
				let user_token = getUInfo().token

				let res = await that.$dsChatCompletions({
					"model": "deepseek-chat",
					"messages": [
						{ "role": "user", "content": "生成一段朋友圈文案" }
					],
					"stream": false,
				})
				if (res.id) {
					console.log('res.usage.total_tokens = ', res.usage.total_tokens);
					this.message = res.choices[0].message.content
					this.message = this.message.replace(/\n/g, '<br />');
				} else {
					uni.showToast({ title: 'DS对话失败', icon: 'none' })
				}
			},

			// 接口:提交信息
			async postData() {
				let that = this
				let token = getUInfo().token
				uni.showLoading({ title: '提交中..', mask: true, })
				let img = this.img_url
				let query_num = this.query_num
				let res = await that.$uploadHd({ token, order_sn: this.order_sn, img, query_num })
				console.log('$uploadHd.res = ', res);
				if (res.code == 1) {

				} else {
					uni.showToast({ title: res.msg, icon: 'none' })
				}
			},

			// 接口:睿真图片识别
			async fetchPicWord() {
				let that = this
				uni.showLoading({ title: '识别中..', mask: true, })
				let user_token = getUInfo().token

				let app_key = '60fa2149'
				let app_secret = 'cfbc4284f9140c1c0d5d64be35475d8d'
				let timestamp = (Date.now() / 1000).toFixed(0)
				let image_url = this.img_url
				let token = this.md5(`${app_key}+${timestamp}+${app_secret}`)

				// let res = await that.$fetchPicTable({ app_key, timestamp, image_url, token })
				let res = await that.$fetchPicWord({ app_key, timestamp, image_url, token })
				if (res.result == 1) {
					uni.showToast({ title: res.message, icon: 'none' })
					if (res.response && res.response.data && res.response.data.identify_results) {
						if (res.response.data.identify_results.length > 0) {
							let id_result = res.response.data.identify_results[0]

							// 解析通用文字
							let print_data = id_result.details.print
							console.log('print_data = ', print_data);
							if (print_data && print_data.length > 0) {
								that.analysisPrintData(print_data)
							}

							// 解析表格
							// let tables = id_result.tables
							// if (tables && tables.length > 0) {
							// 	let table_data = tables[0].cells
							// 	if (table_data && table_data.length > 0) {
							// 		that.analysisTableData(table_data)
							// 	}
							// }
						}
					}
				} else {
					uni.showToast({ title: res.message, icon: 'none' })
				}
			},


			md5(str) {
				try {
					return CryptoJS.MD5(str).toString()
				} catch (error) {}
				return 'md5_error'
			}

		}
	}
</script>

<style scoped>
	.content {
		display: flex;
		flex-direction: column;
		position: relative;
		min-height: 100vh;
		background-color: #6974DD;
		/* background-color: #f0f0f0; */
	}

	.main {
		display: flex;
		flex-direction: column;
		margin: 24rpx;
		background-color: white;
		border-radius: 24rpx;
		padding: 24rpx;
	}

	.menu_name {
		margin: 36rpx 0 0 0;
		display: flex;
		align-items: center;
	}

	.sub_menu_name {
		margin: 12rpx 0 0 0;
	}

	.btn_wb {
		width: 25%;
		height: 76rpx;
		line-height: 76rpx;
		color: white;
		text-align: center;
		font-size: 28rpx;
		margin: 24rpx 0 0 0;
		border-radius: 12rpx;
		background: #6974DD;
		margin: 24rpx 0 0 12rpx;
	}

	/* 选择异常原因 */
	.yc_reason {
		display: flex;
		justify-content: space-between;
		height: 76rpx;
		line-height: 76rpx;
		border-radius: 12rpx;
		border: solid 1rpx #ccc;
		margin: 24rpx 0 0 0;
		padding: 0 24rpx 0 24rpx;
	}

	.item_sel_img {
		display: flex;
		width: 100%;
		margin: 12rpx 0 12rpx 0;
	}

	.sel_img_div {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	/* 选择的照片 */
	.sel_img {
		width: 120rpx;
		height: 120rpx;
		margin: 0 0 0 16rpx;
		border: solid 1rpx #999;
		border-radius: 12rpx;
		/* padding: 1rpx; */
	}

	.sel_img_del {
		padding: 6rpx;
		color: orangered;
		margin: 0 0 0 16rpx;
	}

	.btn_sel_media {
		width: 300rpx;
		height: 66rpx;
		line-height: 66rpx;
		font-size: 28rpx;
	}

	.btn_ok {
		height: 88rpx;
		line-height: 88rpx;
		color: white;
		text-align: center;
		font-size: 30rpx;
		margin: 60rpx 0 0 0;
		border-radius: 888rpx;
		background: #6974DD;
	}

	/* pop弹窗样式 */
	.pop_div {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 75vw;
		background-color: white;
	}

	/* 下单模块 */
	.item_div {
		display: flex;
		flex-direction: column;
		margin: 24rpx 24rpx 24rpx 24rpx;
		padding: 24rpx;
		background-color: white;
		border: solid 1rpx #f0f0f0;
		border-radius: 16rpx;
	}

	.item_sub_div {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 96rpx;
		margin: 10rpx 0 0 0;
	}

	.item_sub_txt {
		font-size: 28rpx;
		font-weight: bold;
		margin: 0rpx 0 0 0rpx;
	}

	.et_sub_txt {
		width: 60%;
		height: 100%;
		text-align: right;
		font-size: 28rpx;
		color: #555;
	}
</style>